#include "StringObject.hpp"
#include "../../base/Defind.hpp"
#include "../Tool.hpp"

using namespace DBServer::Database;

void
StringObject::command_excute(CommandRespond& crp, CommandRequest&& crq, com_func_t& cft)
{
    cb_table[cft.second](*this, std::move(crq), crp);
}

using Callback = std::function<void(StringObject&, CommandRequest&&, CommandRespond&)>;
std::unordered_map<int, Callback> StringObject::cb_table([]{

    std::unordered_map<int, Callback> temp;
    temp[COMMAND_GET] = [](StringObject &so, CommandRequest&& crq, CommandRespond& crp) {
        crp.respond = so.get();
    };

    temp[COMMAND_SET] = [](StringObject &so, CommandRequest&& crq, CommandRespond& crp) {
        so.set(std::move(crq.command[COMMAND_VALUE]));
        crp.respond = std::string(OK);
    };

    temp[COMMAND_SLEN] = [](StringObject &so, CommandRequest&& crq, CommandRespond& crp) {
        int len = so.slen();
        crp.respond = Translator::int_to_string(len);
    };

    temp[COMMAND_SAPPEND] = [](StringObject &so, CommandRequest&& crq, CommandRespond& crp) {
        if (crq.command[COMMAND_VALUE].size() == 0)
        {
            crp.respond = std::string(SAPPEND_NULL);
            return;
        }
        so.append(std::move(crq.command[COMMAND_VALUE]));
        crp.respond = so.get();
    };

    temp[COMMAND_SCOMPARE] = [](StringObject &so, CommandRequest&& crq, CommandRespond& crp) {
        bool is_simple = so.compare(std::move(crq.command[COMMAND_VALUE]));
        if (is_simple)
        {
            crp.respond = SCOMPARE_TRUE;
        }
        else 
        {
            crp.respond = SCOMPARE_FALSE;
        }
    };

    temp[COMMAND_SCLEAR] = [](StringObject &so, CommandRequest&& crq, CommandRespond& crp) {
        so.clear();
        crp.respond = std::string(OK);
    };

    return temp;
}());
